import {Result} from '@/base/Result';
import {request} from '@/base/Request';
import {Page} from '@/base/Page';
import {Role} from '@/base/model/Role';
import {TableSort} from '@/base/TableSort';
import {isEmpty} from '@/base/util/Strings';

export function getRoleList(params: {
  pageIndex: number,
  pageSize: number,
  name?: string,
  companyId?: number[]
}): Promise<Result<Page<Role>>> {
  Object.assign(params, TableSort());
  let companyIdString = '';
  if (params.companyId && params.companyId.length > 0) {
    companyIdString = params.companyId.map(x => 'companyId=' + x).join('&');
    delete params.companyId;
  }
  return request.getPage(Role, '/api/role?' + companyIdString, {params});
}

export function getRole(id: number): Promise<Result<Role>> {
  return request.get(Role, `/api/role/${id}`);
}

export function putRole(id: number, params: {
  description: string,
  name: string
}): Promise<Result<Role>> {
  let formData = new FormData();
  Object.keys(params).forEach(x => {
    formData.append(x, params[x]);
  });
  return request.put(Role, `/api/role/${id}`, formData);
}

export function putRoleRes(params: {
  id: number,
  res: Array<string>
}): Promise<Result<Role>> {
  let formData = new FormData();
  const res = params.res.join(',').split(',').filter(x => !isEmpty(x));
  delete params.res;

  Object.keys(params).forEach(x => {
    formData.append(x, params[x]);
  });

  if (res.length > 0) {
    res.forEach(x => {
      formData.append('res', x);
    });
  } else {
    formData.append('res', '');
  }

  return request.put(Role, '/api/role/res', formData);
}

export function postRole(params: {
  description: string,
  name: string
}): Promise<Result<Role>> {
  let formData = new FormData();
  Object.keys(params).forEach(x => {
    formData.append(x, params[x]);
  });
  return request.post(Role, '/api/role', formData);
}

export function deleteRole(id: number): Promise<Result<void>> {
  return request.delete(`/api/role/${id}`);
}
